import React, { PureComponent } from 'react';
import { Table } from 'antd';
import styles from './index.less';

function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps = nextProps => {
    // clean state
    const { props } = this;
    if (props && props.selectedRows && nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  };

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys } = this.state;
    const {
      data: { list, pagination },
      loading,
      columns,
      rowKey,
      selectedRows,
      addNum,
      size,
      scroll,
      footer,
      bordered,
    } = this.props;

    let paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: total => '共 ' + total + ' 条记录',
      ...pagination,
    };
    if (pagination === false) {
      paginationProps = false;
    }

    let rowSelection = null;
    if (selectedRows) {
      rowSelection = {
        selectedRowKeys,
        onChange: this.handleRowSelectChange,
        getCheckboxProps: record => ({
          disabled: record.disabled,
        }),
      };
    }

    // 添加记录序号
    const newColumns = [...columns]; // 默默地复制一份，不污染涞源
    if (addNum !== false && addNum !== 'false') {
      if (columns[0].dataIndex !== 'id_prikey') {
        // 只添加一次
        newColumns.unshift({
          title: '序号',
          dataIndex: 'id_prikey',
          width: 62,
          render: text => <span style={{ color: 'darkgray' }}>{text}</span>,
        });
      }
      for (let i = 0; i < list.length; i += 1) {
        list[i].id_prikey = i + 1;
      }
    }

    return (
      <div className={styles.standardTable}>
        <Table
          loading={loading}
          rowKey={rowKey || 'id'}
          rowSelection={rowSelection}
          dataSource={list}
          columns={newColumns}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          size={size}
          scroll={scroll}
          bordered={bordered}
          footer={footer ? () => footer : null}
        />
      </div>
    );
  }
}

export default StandardTable;
